package com.yun.zf.admin.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.github.xiaoymin.knife4j.annotations.DynamicParameter;
import com.github.xiaoymin.knife4j.annotations.DynamicParameters;
import com.yun.zf.admin.service.*;
import com.yun.zf.common.admin.domain.SysAgent;
import com.yun.zf.common.admin.dto.community.CommunityBasicDto;
import com.yun.zf.common.admin.dto.community.CommunityDto;
import com.yun.zf.common.admin.model.community.CommunityAddMo;
import com.yun.zf.common.admin.model.community.CommunityBasicMo;
import com.yun.zf.common.admin.model.community.CommunitySchoolsMo;
import com.yun.zf.common.admin.model.community.CommunitySearchResMo;
import com.yun.zf.common.admin.model.search.CommunitySearchMo;
import com.yun.zf.common.annotation.LogPrint;
import com.yun.zf.common.app.dto.detail.CommunityNearByDto;
import com.yun.zf.common.constant.Constants;
import com.yun.zf.common.esRes.CommunityResMo;
import com.yun.zf.common.vo.Response;
import com.yun.zf.system.alimap.Tip;
import com.yun.zf.system.security.utils.SecurityUtils;
import com.yun.zf.system.service.SysAgentService;
import com.yun.zf.system.service.ZfSearchService;
import com.yun.zf.system.utils.AliyunOssUtil;
import com.yun.zf.system.utils.AmapUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@Api(value = "", tags = "小区管理")
@RequestMapping("/system/community")
@Slf4j
public class CommunityController extends BaseController {

    @Autowired
    private ZfCommunityService communityService;
    @Autowired
    private ZfSearchService searchService;
    @Autowired
    private AmapUtil amapUtil;
    @Autowired
    private ZfHouseDocumentInfoService documentInfoService;
    @Autowired
    private SysAgentService agentService;
    @Autowired
    private ZfHousePictureService pictureService;
    @Autowired
    private AliyunOssUtil ossUtil;
    @Autowired
    private ZfCommunityPictureService communityPictureService;
    @Autowired
    private ZfSchoolsService schoolsService;
    @Autowired
    private ZfDeptCommunityService deptCommunityService;


    /**
     * 录入基本信息只有销售代表，客服人员，管理员可以录入
     *
     * @return
     */
    @PostMapping("/addBasicCommunity")
    @ApiOperation(value = "录入小区基本信息")
    @ApiOperationSupport(order = 1)
    @PreAuthorize("@ss.hasAnyRoles('service,admin,sales')")
    public Response addBasicCommunity(@RequestBody CommunityBasicMo basicMo) {
        try {
            if (basicMo.getCity() == null || basicMo.getCity().length != 2) {
                return Response.error("确认城市信息是否正确");
            }
            Long id = communityService.addBasicCommunity(basicMo.getCommunityName(), basicMo.getCity(), basicMo.getDeptId());
            if (id.longValue() == -1L) {
                return Response.error("小区新增失败");
            }
            return Response.success(id);
        } catch (Exception e) {
            return Response.error("小区新增失败");
        }
    }

    @PostMapping("/communityOfMine")
    @ApiOperation(value = "我的小区")
    @ApiOperationSupport(order = 2)
    public Response communityOfMine() {
        try {
            // 当前登录人的门店小区
            Long userId = SecurityUtils.getLoginUser().getUserId();
            // 获取业务员所在的部门
            SysAgent agent = agentService.getInfoByUserId(userId);
            // 根据部门id 查询小区id集合
            List<Long> cids = deptCommunityService.getCommunitys(agent.getDeptId());
            if (cids.size() == 0) {
                return Response.error("当前门店还未录入小区信息，请联系相关人员尽快录入！");
            }
            List<CommunityNearByDto> list = communityService.getBasicCommunity(cids);
            return Response.success(list);
        } catch (Exception e) {
            return Response.error("查询异常");
        }
    }


    /**
     * 查询小区详情信息
     *
     * @return
     */
    @PostMapping("/getCommunityById")
    @ApiOperation(value = "小区详情信息")
    @ApiOperationSupport(order = 2)
    @DynamicParameters(name = "SendOrderMapModel", properties = {
            @DynamicParameter(name = "communityId", value = "小区编号", example = "000111", required = true)
    })
    public Response getCommunityById(@RequestBody Map<String, String> map) {
        try {
            CommunityDto community = communityService.getCommunityById(Long.parseLong(map.get("communityId")));
            return Response.success(community);
        } catch (Exception e) {
            return Response.error("查询异常");
        }
    }

    @PostMapping("/motifyCommunityById")
    @ApiOperation(value = "编辑基本概况信息")
    @ApiOperationSupport(order = 4)
    @LogPrint(description = "编辑基本概况信息")
    public Response motifyCommunityById(@Validated @RequestBody CommunityAddMo community) {
        try {
            Response res = checkStatus(Long.parseLong(community.getId()));
            if (res != null) {
                return res;
            }
            communityService.motifyCommunity(community);
            return Response.success("修改成功");
        } catch (Exception e) {
            return Response.error("修改异常");
        }
    }

    @PostMapping("/getCommunityBasic")
    @ApiOperation(value = "获取基本信息")
    @ApiOperationSupport(order = 2)
    @DynamicParameters(name = "SendOrderMapModel", properties = {
            @DynamicParameter(name = "communityId", value = "小区编号", example = "000111", required = true)
    })
    public Response getCommunityBasic(@RequestBody Map<String, String> map) {
        try {
            return Response.success(communityService.getBasic(Long.parseLong(map.get("communityId"))));
        } catch (Exception e) {
            return Response.error("基本信息获取异常");
        }
    }

    @PostMapping("/getCommunityPic")
    @ApiOperation(value = "获取图片信息")
    @ApiOperationSupport(order = 2)
    @DynamicParameters(name = "SendOrderMapModel", properties = {
            @DynamicParameter(name = "communityId", value = "小区编号", example = "000111", required = true),
            @DynamicParameter(name = "type", value = "图片类型", example = "1", required = true)
    })
    public Response getCommunityPic(@RequestBody Map<String, String> map) {
        try {
            return Response.success(communityPictureService.getCommunityPicture(Long.parseLong(map.get("communityId")), Integer.parseInt(map.get("type"))));
        } catch (Exception e) {
            return Response.error("图片信息获取异常");
        }
    }


    @PostMapping("/uploadPic")
    @ApiOperation(value = "上传图片信息")
    @PreAuthorize("@ss.hasAnyRoles('manager,admin')")
    @ApiOperationSupport(order = 3)
    @LogPrint(description = "图片上传")
    public Response uploadPic(@RequestParam("files") MultipartFile[] files, HttpServletRequest request) {
        Response res = null;
        try {
            // 1 图片上传
            if (files != null && files.length == 0) {

                return Response.error("请上传图片");
            }
            String cat = request.getParameter("cat");

            switch (cat) {
                case "C":
                    res = communityPictureService.communityPic(files, request);
                    break;
                // 房源图片上传files = {MultipartFile[2]@22403}
                case "H":
                    res = pictureService.uploadHousepic(files, request, prov, aCode);
                    break;
                // 房产证上传
                case "HC":
                    res = documentInfoService.uploadDoucument(files, request, prov, aCode);
                    break;

            }
        } catch (Exception e) {
            return Response.error("上传失败");
        }
        return res;
    }

    @PostMapping("/delCommunityPic")
    @ApiOperation(value = "删除图片信息")
    @DynamicParameters(name = "SendOrderMapModel", properties = {
            @DynamicParameter(name = "cat", value = "上传文件分类", example = "C", required = true)
    })
    public Response delCommunityPic(@RequestBody Map<String, String> map) {

        Response res = null;
        try {
            String cat = map.get("cat");
            switch (cat) {
                case "C":
                    res = communityPictureService.delCommunityPicture(map.get("ids"));
                    break;
                // 房源图片上传
                case "H":
                    res = pictureService.delHousepic(map.get("ids"), prov, aCode);
                    break;
                // 房产证上传
                case "HC":
                    res = documentInfoService.delDoucument(map.get("ids"), prov, aCode);
                    break;
            }
            return res;
        } catch (Exception e) {
            return Response.error("删除异常");
        }
    }

    @PostMapping("/upload")
    @ApiOperation(value = "上传图片信息")
    @ApiOperationSupport(order = 3)
    @LogPrint(description = "图片上传")
    public Response upload(@RequestParam("files") MultipartFile[] files, HttpServletRequest request) {
        try {
            // 1 图片上传
            if (files != null && files.length == 0) {
                return Response.error("请上传图片");
            }
            List<Map<String, String>> pictureList = new ArrayList<>();
            Map<String, String> map = new HashMap<>();
            String cat = request.getParameter("cat");
            String bucket = "";
            String folder = "";
            String other = "";
            switch (cat) {
                case "P":
                    bucket = Constants.BUCKET_AGENT;
                    folder = Constants.FOLDER_AGENT;
                    other = String.valueOf(SecurityUtils.getLoginUser().getUserId());
                    break;
            }
            for (MultipartFile file : files
            ) {
                map = ossUtil.uploadObject2OSS(file, bucket, folder + "/" + other);
                if (map != null) {
                    pictureList.add(map);
                }
            }
            return Response.success(map);
        } catch (Exception e) {
            return Response.error("上传失败");
        }
    }




    @PostMapping("/getTips")
    @ApiOperation(value = "输入提示")
    @ApiOperationSupport(order = 5)
    @LogPrint(description = "输入提示")
    @DynamicParameters(name = "SendOrderMapModel", properties = {
            @DynamicParameter(name = "name", value = "输入内容", example = "C", required = true),
            @DynamicParameter(name = "adcode", value = "城市代码", example = "C", required = true),
            @DynamicParameter(name = "location", value = "经纬度", example = "C", required = true)
    })
    public Response getSchools(@RequestBody Map<String, String> map) {
        String school = map.get("name");
        String adcode = map.get("adcode");
        String location = map.get("location");
        if (StringUtils.isBlank(school) || StringUtils.isBlank(adcode)) {
            return Response.error("缺少必要参数");
        }
        JSONObject object = amapUtil.inputtips(school, "", location, adcode, true, "poi");
        String tips = object.getString("tips");
        List<Tip> dataArr = JSONArray.parseArray(tips, Tip.class);
        return Response.success(dataArr);
    }

    @PostMapping("/addSchoolInfo")
    @ApiOperation(value = "补充学校信息")
    @ApiOperationSupport(order = 6)
    @LogPrint(description = "补充学校信息")
    public Response addSchoolInfo(@Validated @RequestBody CommunitySchoolsMo schoolMo) {
        Response res = checkStatus(Long.parseLong(schoolMo.getCommunityId()));
        if (res != null) {
            return res;
        }
        try {
            schoolsService.addCommunitySchools(schoolMo);
            return Response.success("操作成功");
        } catch (Exception e) {
            return Response.error("修改异常");
        }
    }

    @PostMapping("/communitySchool")
    @ApiOperation(value = "获取学区信息")
    @ApiOperationSupport(order = 6)
    @LogPrint(description = "获取学区信息")
    @DynamicParameters(name = "SendOrderMapModel", properties = {
            @DynamicParameter(name = "communityId", value = "小区编号", example = "000111", required = true)
    })
    public Response communitySchool(@RequestBody Map<String, String> map) {
        try {
            return Response.success(schoolsService.getCommunitySchools(Long.parseLong(map.get("communityId"))));
        } catch (Exception e) {
            return Response.error("数据返回异常");
        }
    }

    @PostMapping("/delcommunitySchool")
    @ApiOperation(value = "删除学区信息")
    @ApiOperationSupport(order = 6)
    @LogPrint(description = "删除学区信息")
    public Response delcommunitySchool(@RequestBody Map<String, String> map) {
        // todo 待传小区id 进行发布验证
        try {
            schoolsService.delSchoolById(Long.parseLong(map.get("id")));
            return Response.success("删除成功");
        } catch (Exception e) {
            return Response.error("删除失败");
        }
    }


    /**
     * 社区发布推送至搜索中心
     *
     * @return
     */
    @PostMapping("/publishCommunity")
    @ApiOperation(value = "社区发布")
    @DynamicParameters(name = "SendOrderMapModel", properties = {
            @DynamicParameter(name = "id", value = "小区编号", example = "000111", required = true)
    })
    public Response publishCommunity(@RequestBody Map<String, String> map) {
        communityService.publishCommunity(Long.parseLong(map.get("id").toString()));
        return Response.success();
    }


    /**
     * 根据城市小区名称信息自动补全
     *
     * @return ，显示列表可参考贝壳小程序
     */
    @PostMapping("/communitySuggest")
    @ApiOperation(value = "搜索框自动补全提示-----待切换到 公共搜索 communitySuggest")
    public Response communitySuggest(String title) {
        // todo
        List<Map<String, String>> suggests = communityService.communitySuggest(title, aCode);
        return Response.success(suggests);
    }

    @PostMapping("/searchCommunitys")
    @ApiOperation(value = "搜索查询列表 -- 待切换到公共搜索")
    public Response searchCommunitys(@RequestBody CommunitySearchMo communitySearchMo) {
        //todo
        communitySearchMo.setCityCode(String.valueOf(aCode));
        // 1、 查询es中符合条件的小区Id信息
        Map<String, Object> community = communityService.searchCommunitys(communitySearchMo);
        if (community == null) {
            return Response.success("未搜索到符合条件的数据");
        }
        //2、查询小区基本信息
        List<CommunityResMo> esResList = (List<CommunityResMo>) community.get("records");
        if (esResList.size() <= 0) {
            return Response.success("未查询到符合条件的小区信息");
        }
        List<Long> ids = new ArrayList<>();
        for (CommunityResMo res : esResList) {
            ids.add(res.getCid());
        }

        List<CommunityNearByDto> list = communityService.getBasicCommunity(ids);
        CommunitySearchResMo searchResMo = new CommunitySearchResMo();
        searchResMo.setTotal(Integer.parseInt(community.get("total").toString()));
        searchResMo.setTotalPage(Integer.parseInt(community.get("totalPage").toString()));
        searchResMo.setCurPage(Integer.parseInt(community.get("current").toString()));
        searchResMo.setCommunitySearchListMos(list);
        return Response.success(searchResMo);
    }

    // 获取小区户型图
    @PostMapping("/communityHuXing")
    @ApiOperation(value = "获取小区户型图")
    @DynamicParameters(name = "SendOrderMapModel", properties = {
            @DynamicParameter(name = "communityId", value = "小区编号", example = "000111", required = true),
            @DynamicParameter(name = "type", value = "类型", example = "000111", required = true)
    })
    public Response communityHuXing(@RequestBody Map<String, String> map) {
        if (StringUtils.isBlank(map.get("communtyId")) || StringUtils.isBlank(map.get("type"))) {
            return Response.error("缺少必要参数");
        }
        return Response.success(communityPictureService.getCommunityPicture(Long.parseLong(map.get("communtyId")), Integer.parseInt(map.get("type"))));
    }


    /**
     * 如果小区已经发布，则不可在进行修改
     *
     * @param community
     * @return
     */
    public Response checkStatus(Long community) {
        CommunityBasicDto basicDto = communityService.getBasic(community);
        if ("on".equals(basicDto.getCStatus())) {
            return Response.error("当前不可在进行编辑");
        }
        return null;
    }

}
